package com.atsmart.app.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.atsmart.app.R;
import com.atsmart.app.model.ProductGroupInfo;
import com.atsmart.app.model.ProductGroupListInfo;

public class ProductAdapter extends LoadingAdapter {
	private ProductGroupListInfo datasource;
	private LayoutInflater inflater;


	public ProductAdapter(ProductGroupListInfo datasource, Context context) {
		this.datasource = datasource;
		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public void appendDataSource(ProductGroupListInfo appendData) {
		datasource.getProducts().addAll(appendData.getProducts());
	}

	private static class ViewHolder {
		TextView name;
		ImageView img;
	}

	@Override
	public int getCount() {
		if (datasource.getProducts() == null
				|| datasource.getProducts().size() == 0) {
			return 0;
		}

		if (delegate != null && delegate.needLoading()) {
			return datasource.getProducts().size() + 1;
		} else {
			return datasource.getProducts().size();
		}
	}

	@Override
	public Object getItem(int position) {
		if (datasource.getProducts() == null
				|| position == datasource.getProducts().size()
				&& delegate != null && delegate.needLoading()) {
			return null;
		}
		return datasource.getProducts().get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View loadingRow = super.getView(position, convertView, parent);
		if (loadingRow != null) {
			return loadingRow;
		}
		return getView(position, convertView);
	}

	private View getView(final int position, View convertView) {
		ViewHolder vh;
		if (convertView == null || convertView.getTag() == null) {
			convertView = inflater.inflate(R.layout.product_list_item_layout,
					null);
			vh = new ViewHolder();
			vh.name = (TextView) convertView.findViewById(R.id.txt_client_name);
			vh.img = (ImageView) convertView.findViewById(R.id.fileimg);
			convertView.setTag(vh);
		} else {
			vh = (ViewHolder) convertView.getTag();
		}
		ProductGroupInfo clientInfo = datasource.getProducts().get(position);
		vh.name.setText(clientInfo.getName()+"("+clientInfo.getNums()+")");
		if(clientInfo.getType()==1){
			vh.img.setBackgroundResource(R.drawable.open_file);
		}else{
			vh.img.setBackgroundResource(R.drawable.folder);
		}
		if(position%2==1){
			convertView.setBackgroundResource(R.color.bottom_gray);
		}else{
			convertView.setBackgroundResource(R.color.white);
		}
		return convertView;
	}

	@Override
	protected boolean isLoadingRow(int position) {
		return position >= datasource.getProducts().size();
	}

}
